<?php
declare (strict_types = 1);

namespace app\middleware;

use think\Request;
use think\Response;

class CheckToken
{
    public function handle(Request $request, \Closure $next): Response
    {
        $token = $request->header('Authorization');
        if (!$token || strlen($token) < 20) {
            return json(['code' => 4001, 'message' => '登录凭据不存在，请重新登录'], 403);
        }
        // 检查 token 是否包含 Bearer 前缀
        if (str_starts_with($token, 'Bearer')) {
            $token = substr($token, 7); // 去除 Bearer 前缀
        }else{
            return json(['code' => 4001, 'message' => '登录凭据格式错误，请重新登录'], 403);
        }
        try {
            verifyToken($token);
        } catch (\Exception $e) {
            return json(['code' => 4001, 'message' => $e->getMessage()], 403);
        }
        return $next($request);
    }
}